<template>
  <div class="read">
    <div class="title">
      <div class="titleBox flex" color="primary" style="width: 100%;">
        <div class="read_title">
          <span>{{chapterName}}</span>
        </div>
      </div>
    </div>
    <div class="loadmore-wrap">
      <mu-container ref="container" class="loadmore-content">
        <mu-load-more :loaded-all='finished' :loading="loading" @load="next">
          <!-- 显示当前的漫画列表 -->
          <div class="flex flex-column" style='align-items:center'>
            <div class='ty_item' v-for="item in mhList" :key='item.id'>
              <img :data-key='item.key' v-lazy="item.src" v-lazy:background-image='item.src'>
            </div>
          </div>
        </mu-load-more>
        <div v-if="finished" class='finished'>已全部加载 </div>
      </mu-container>
    </div>
    <div class="staticBox flex">
      <span class="title">{{chapterName}}</span>
      <span class="catalog">{{curPage}}/{{endNum}}</span>
      <span class="time">{{currentTime}}</span>
    </div>
  </div>
</template>
<style>
  @import './read';

</style>
<script>
  import date from './../commponent/utils/date';
  export default {
    data() {
      return {
        finished: false,
        loading: false,
        mhList: [],
        catalogNum: 0,
        catalogLen: 0,
        catalogtitle: '',
        endNum: 0,
        catalogList: [],
        cmiclf: null,
        currentTime: '',
        curcatalogDom: [],
        curPage: 1,
        chapterName: '',
        comicName: '',
        his_comic: [],
        reload: false,
        comicId: '',
      };
    },
    methods: {
      next() {
        if (this.catalogNum > this.catalogLen) {
          alert('已经阅读完了');
          return false;
        } else {
          this.catalogNum += 1;
          this.loadcmic();
        }
        this.$router.push('/main/read?comicId=' + this.comicId + 'title=' + this.chapterName);
      },
      prev() {
        if (this.catalogNum == 0) {
          alert('已经是第一话了');
          return false;
        } else {
          this.catalogNum -= 1;
          this.loadcmic(0);
        }
        this.$router.push('/main/read?title=' + this.chapterName);
      },
      loadcmic(way) {
        this.curcatalogDom = [];
        let f = this.catalogList[this.catalogNum];
        this.chapterName = f.chapter_name;
        this.title = this.chapterName;
        this.endNum = f.end_num;
        if (way === 0) {
          for (let i = 1; i <= f.end_num; i++) {
            let url = `https://mhpic.jumanhua.com${f.rule}-kmh.low.webp`
            let key = this.catalogNum + '-' + i;
            this.mhList.unshift({
              key: key,
              src: url.replace('$$', i)
            });
          }
        } else {
          for (let i = 1; i <= f.end_num; i++) {
            let url = `https://mhpic.jumanhua.com${f.rule}-kmh.low.webp`
            let key = this.catalogNum + '-' + i;
            this.mhList.push({
              key: key,
              src: url.replace('$$', i)
            });
          }
        }
        setTimeout(() => {
          for (let i = 1; i <= this.endNum; i++) {
            let dom = document.querySelector('img[data-key="' + this.catalogNum + '-' + i + '"]');
            this.curcatalogDom.push(dom)
          }
        }, 1000);
        // this.$vlf.createInstance({
        //   name: 'mh',
        //   storeName: 'comicInfo',
        // }).then(info => {
        //   info.setItem('catatitle', this.chapterName);
        // });
        this.cmiclf.setItem('curCatalog', f);
      },
      scrollfun() {
        let timetag = false;
        let timer = setTimeout(() => {
          if (!timetag) {
            timetag = true;
            clearTimeout(timer);
            let curTop = document.querySelector('.container').scrollTop;
            for (let i = 1; i <= this.endNum; i++) {
              if (!this.curcatalogDom[i]) {
                this.curPage = i;
                this.cmiclf.setItem('read',
                  `${this.catalogNum}-${this.curPage}`);
                break;
              } else if (this.curcatalogDom[i - 1].getBoundingClientRect().y < curTop <
                this.curcatalogDom[i].getBoundingClientRect().y) {
                this.curPage = i;
                this.cmiclf.setItem('read',
                  `${this.catalogNum}-${this.curPage}`);
                break;
              }
            }
          }
          timetag = false;
        }, 500);
      }
    },
    mounted() {
      window.addEventListener('scroll', this.scrollfun, true);
    },
    destroyed() {
      // 判断是否存在，若存在，则删除该条数据然后在其尾部添加
      // this.infolf.getItem('comicId').then(comicId => {
      //   if (!comicId) return;

      // })
      this.his_comic.forEach((item, index) => {
        if (this.comicId == item.comicId) {
          this.his_comic.splice(index, 1);
        }
      })
      this.his_comic.push({
        comicId: this.comicId,
        name: this.comicName,
        title: this.chapterName,
        progress: `${this.catalogNum}-${this.curPage}`
      })
      this.infolf.setItem('history', this.his_comic)
      window.removeEventListener('scroll', this.scrollfun, true);
    },
    created() {
      let comicId = this.$route.query.comicId;
      this.comicId = comicId;
      let progress = '';

      this.$vlf.createInstance({
        name: 'mh',
        storeName: 'comicInfo',
      }).then(info => {
        this.infolf = info;
        // 获取历史缓存信息
        this.infolf.getItem('history').then(his => {
          this.his_comic = his || [];
        })
        if (comicId) {
          this.reload = true;
          this.$progress.start();
          this.$http.get('http://y.yuduo.top/index/manhua/getMhInfo', {
            params: {
              comicId: comicId
            }
          }).then(res => {
            // info.getItem('comicId').then((val) => {
            this.his_comic.forEach(item => {
              if (comicId == item.comicId) {
                this.catalogtitle = item.title;
                this.comicName = item.name;
                progress = item.progress;
              }
            })
            let data = res.data;
            if (typeof data == 'string') {
              data = JSON.parse(data).data;
            };
            let list = data['comic_chapter'].reverse();
            this.catalogList = list;
            this.catalogLen = list.length;
            this.catalogtitle = this.$route.query.title || this.catalogtitle;
            this.comicName = this.$route.query.comicName || this.comicName;
            this.catalogList.forEach((item, index) => {
              if (item.chapter_name == this.catalogtitle) {
                this.catalogNum = index;
              }
            })
            this.loadcmic();
            // setTimeout(() => {
            //   let tempdom = document.querySelector(
            //     'img[data-key="' +
            //     progress +
            //     '"]');
            //   if (!tempdom) return;
            //   let top = tempdom.getBoundingClientRect().y;
            //   document.querySelector('.container').scrollTop = top;
            // }, 2000);
            this.$progress.done();
          })
          // })
        }
        // if (!this.reload) {
        //   debugger;
        //   info.getItem('comicId').then((val) => {
        //     this.his_comic.forEach(item => {
        //       if (item.comicId == val) {
        //         this.catalogtitle = item.title;
        //         this.comicName = item.name;
        //       }
        //     })
        //   })
        //   info.getItem('list').then(list => {
        //     this.catalogList = list;
        //     this.catalogLen = list.length;
        //     this.catalogtitle = this.$route.query.title || this.catalogtitle;
        //     this.comicName = this.$route.query.comicName || this.comicName;
        //     this.catalogList.forEach((item, index) => {
        //       if (item.chapter_name == this.catalogtitle) {
        //         this.catalogNum = index;
        //       }
        //     })
        //     this.loadcmic();
        //   });
        // }
        this.$vlf.createInstance({
          name: 'mh',
          storeName: 'readhis',
        }).then(mhs => {
          this.cmiclf = mhs;
          // setTimeout(() => {
          //   this.cmiclf.getItem('read').then(val => {
          //     let tempdom = document.querySelector(
          //       'img[data-key="' +
          //       val +
          //       '"]');
          //     if (!val || !tempdom) return;
          //     let top = tempdom.getBoundingClientRect().y;
          //     document.querySelector('.container').scrollTop = top;
          //   })
          // }, 2000);
        });

      });

      this.currentTime = date(new Date(), 'HH:mm:ss');
      setInterval(() => {
        this.currentTime = date(new Date(), 'HH:mm:ss');
      }, 1000);
      // 设置滚动条位置
    }
  };

</script>
